package com.xiaoma.bio;



import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 */

public class BIOServer {
    public static void main(String[] args) throws Exception {
        //创建一个线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        //创建一个服务器监听6666端口
        final ServerSocket server = new ServerSocket(6666);
        System.out.println("服务器启动了。。。");
        while (true){
            //监听
            System.out.println("等待连接");
             Socket socket = server.accept();
            System.out.println("连接到了一个客户端");
            //线程池创建一个线程与之通讯
            threadPool.submit(()->handler(socket));
        }

    }
    public  static  void  handler(Socket socket){
        try {
            System.out.println("当前线程为:"+Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            InputStream in = socket.getInputStream();
            while (true){
                System.out.println("read.......");
                int read = in.read(bytes);
                if (read!=-1) {
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
